package com.dycn.service;

import com.dycn.dao.RedisDao;
import com.dycn.util.AppResultData;
import com.dycn.util.OkhttpUtil;
import com.dycn.util.RandomString;
import com.dycn.util.SHA1;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeixinService {

    @Autowired
    RedisDao redisDao;

    public Map<String,String> wxConfig(HttpServletRequest request){

        String token=redisDao.getValue("wxtoken");
       // String url="http://wx.sxbq998.cn/api/cyuser/xuan";
        String url = "";
        url = request.getScheme() +"://" + request.getServerName()
                + ":" +request.getServerPort()
                + request.getServletPath();
        if(request.getServerPort()==80){
            url = request.getScheme() +"://" + request.getServerName()
                    + request.getServletPath();
        }
        if (request.getQueryString() != null){
            url += "?" + request.getQueryString();
        }
       // url="http://wx.sxbq998.cn/api/cyuser/xuan";
        String wxConfig="";
        String noncestr="";
        String timestamp="";
        if(token==null){
                token=OkhttpUtil.getInstance().getAccessToken();
                redisDao.putSecondValue("wxtoken",token,7190);
            //String ticket=redisDao.getValue("wxticket");
            //if(ticket==null){
                String  ticket=OkhttpUtil.getInstance().getTicket(token);
                redisDao.putSecondValue("wxticket",ticket,7190);
            //}
            noncestr=RandomString.randomString(10);
            redisDao.putSecondValue("noncestr",noncestr,7190);
            timestamp=System.currentTimeMillis()/1000+"";
            redisDao.putSecondValue("timestamp",timestamp,7190);
            //redisDao.putSecondValue("url",url,7190);
            wxConfig=SHA1.sha(noncestr,ticket,timestamp,url);
            //redisDao.putSecondValue("wxConfig",wxConfig,7190);
        }else {
            noncestr=redisDao.getValue("noncestr");
            String ticket=redisDao.getValue("wxticket");
            timestamp=redisDao.getValue("timestamp");
            wxConfig=SHA1.sha(noncestr,ticket,timestamp,url);
        }
        Map<String,String> map=new HashMap<>();
        map.put("wxConfig",wxConfig);
        map.put("noncestr",noncestr);
        map.put("timestamp",timestamp);
        map.put("url",url);
        map.put("appid",OkhttpUtil.APPID);
       // map.put("num",num);
       // map.put("share",share);
       return map;
    }
}
